module DisOrder
  class Init
    extend Helpers

    def self.init(name="./")
      FileUtils.mkdir_p(File.join(Dir.pwd, name)) if name != "./"
      Dir.chdir(name) if name != "./"

      FileUtils.mkdir_p(File.join(Dir.pwd, "articles"))
      FileUtils.mkdir_p(File.join(Dir.pwd, "static"))
      FileUtils.mkdir_p(File.join(Dir.pwd, "meta"))

      defaults_path = File.expand_path(File.dirname(__FILE__))

      FileUtils.cp_r(File.join(defaults_path, 'defaults', 'themes'), File.join(Dir.pwd, "themes"))

      FileUtils.copy_file(File.join(defaults_path, 'defaults', 'config.yml'), File.join(Dir.pwd, "config.yml") )

      initStaticPage("About")
      initArticle("Hello World")
    end

    def self.initArticle(name)
      generatePage(name, config("metaDataFileArticels"), config("baseArticlesFolder"))
    end

    def self.initStaticPage(name)
      generatePage(name, config("metaDataFilePages"), config("baseStaticFolder"))
    end

    def self.generatePage(name, metaFile, pageFolder)
      metaPath = config("baseMetaDataFolder") + "/" + metaFile

      pages = File.exist?(metaPath) ? YAML.load_file(metaPath) : Hash.new

      sanitizedName = sanitize_filename(name)

      new_page = {"name" => name, "date" => Date.today, "folder" => sanitizedName, "url" =>sanitizedName}

      pages[sanitizedName] = new_page

      File.open(config("baseMetaDataFolder") + "/"+ metaFile, mode: "w:UTF-8") do |f|
          f.write YAML.dump(pages)
      end

      @name   = name
      @folder = new_page["folder"]
      @pageFolder = pageFolder

      defaults_path = File.expand_path(File.dirname(__FILE__))
      template = ERB.new(File.new(File.join(defaults_path, 'defaults', 'articlesBase.md.erb'), encoding: "UTF-8").read, 0, "%<>")
      result = template.result(binding)

      FileUtils.mkdir_p(File.join(Dir.pwd, pageFolder, @folder))

      File.open("#{pageFolder}/#{@folder}/index.md", mode: "w:UTF-8") do |f|
        f.write result
      end
    end
  end
end